//
//  CSFacebookShareManager.swift
//  Cycling
//
//  Created by CSS on 5/18/23.
//

import Foundation
import UIKit

import FBSDKShareKit
import SDWebImage

public class CSFacebookShareManager: NSObject {
    
    private var imageStrings: [String]?
    private var sharedComplete: ((Bool, Bool) -> Void)?
    private var sharedDialog: ShareDialog?
    
    @objc public static let shared = CSFacebookShareManager()
    
    @objc public class func shared(withImageStrings imageStrings: [String], fromViewController: UIViewController, complete:((Bool, Bool) -> Void)? = nil) {
        shared.shared(withImageStrings: imageStrings, fromViewController: fromViewController, complete: complete)
    }
    
    @objc public func shared(withImageStrings imageStrings: [String], fromViewController: UIViewController, complete:((Bool, Bool) -> Void)? = nil) {
        self.imageStrings = imageStrings
        sharedComplete = complete

//        for imageString in imageStrings {
//            if let contentURL = URL(string: imageString) {
//                let photo = SharePhoto(imageURL: contentURL, userGenerated: false)
//                photos.append(photo)
//            }
//        }
        downloadImages(withImageUrls: imageStrings) { images in
            
            var photos: [SharePhoto] = []
            for image in images {
                let photo = SharePhoto(image: image, userGenerated: true)
                photos.append(photo)
            }
            
            let sharedContent = SharePhotoContent()
            sharedContent.photos = photos
            let sharedDialog = ShareDialog(fromViewController: fromViewController, content: sharedContent, delegate: self)
            sharedDialog.mode = .native
            if !sharedDialog.canShow {
                sharedDialog.mode = .web
            }
            
            self.sharedDialog = sharedDialog
            
            sharedDialog.show()
        }
    }
    
    private func downloadImages(withImageUrls imageUrls: [String], complete:((_ images: [UIImage]) -> Void)?) {
        let group = DispatchGroup()
        let queue = DispatchQueue.global()
        
        var images: [Int : UIImage] = [:]
        
        for imageUrl in imageUrls {
            group.enter()
            queue.async {
                SDWebImageManager.shared.loadImage(with: URL(string: imageUrl), progress: nil) { image, _, _, _, _, imageURL in
                    if let image = image, let imageURL = imageURL, let imageIndex = imageUrls.firstIndex(of: imageURL.absoluteString) {
                        images[imageIndex] = image
                    }
                    group.leave()
                }
            }
        }
        
        group.notify(queue: queue) {
            let requestedImages = images.sorted { $0.key < $1.key }.reduce([UIImage](), {
                if $0.count >= 6 {
                    return $0
                }
                return $0 + [$1.value]
            })
            DispatchQueue.main.async {
                complete?(requestedImages)
            }
        }
    }
    
}

extension CSFacebookShareManager: SharingDelegate {
    public func sharer(_ sharer: FBSDKShareKit.Sharing, didCompleteWithResults results: [String : Any]) {
        sharedComplete?(true, false)
    }
    
    public func sharer(_ sharer: FBSDKShareKit.Sharing, didFailWithError error: Error) {
        let shareError = error as NSError
        if shareError.domain == ShareErrorDomain && shareError.code == 202 {
//            sharedDialog?.mode = .web
//            sharedDialog?.show()
            sharedDialog?.fromViewController?.showAlert(withTitle: YQLocalizedString("Please install the Facebook client to share", comment: ""), message: nil, leftTitle: YQLocalizedString("OK", comment: ""), leftStyle: .destructive, leftBlock: {
                
            }, rightTitle: nil, rightStyle: .destructive, rightBlock: nil)
            sharedComplete?(false, true)
        } else {
            sharedComplete?(false, false)
        }
    }
    
    public func sharerDidCancel(_ sharer: FBSDKShareKit.Sharing) {
        sharedComplete?(false, true)
    }
    
    
}
